package swing.admin.utils;

import java.sql.*;


public class JdbcUtils {

    private static final String driver = "com.mysql.cj.jdbc.Driver";
    private static final String url = "jdbc:mysql://121.43.154.199:3306/sms?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false";
    private static final String username = "root";
    private static final String password = "root@aliyun2023";

    public static Connection getConnection() {
        Connection connection;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }


    public static void close(Connection conn, Statement stmt, ResultSet res) {
        if (res != null) {
            close(res);
        }

        if (stmt != null) {
            close(stmt);
        }

        if (conn != null) {
            close(conn);
        }
    }


    public static void close(Statement stmt) {
        try {
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public static void close(ResultSet res) {
        try {
            res.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public static void close(Connection connection) {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


    public static void begin(Connection conn) {
        if (conn != null) {
            try {
                conn.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void commit(Connection conn) {
        if (conn != null) {
            try {
                conn.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void rollback(Connection conn) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}
